<template>
  <div class="main-content">
    <div class="top">
      <div class="top-op">
        <div class="btn">
          <el-upload :show-file-list="false" :with-credentials="true" :multiple="true" :http-request="addFile"
            :accept="fileAccept">
            <el-button type="primary">
              <span class="iconfont icon-upload"></span>
              上传
            </el-button>
          </el-upload>
        </div>
        <el-button type="danger" @click="batchDeleteFiles">
          <span class="iconfont icon-del"></span>
          批量删除
        </el-button>
        <div class="search-panel">
          <!-- input输入 -->
          <el-input v-model="searchName" clearable placeholder="搜索文件名" @keyup.enter="searchFiles">
            <template #suffix>
              <i class="iconfont icon-search" @click="searchFiles"></i>
            </template>
          </el-input>
        </div>
        <div class="iconfont icon-refresh" @click="refreshFileList"></div>
      </div>
      <div>{{ currentCategoryName }}文件 ({{ total }}个)</div>
    </div>
    <!-- 文件列表 -->
    <div class="file-list" v-if="fileList.length > 0">
      <el-table :data="fileList" style="width: 100%" @row-click="handleRowClick">
        <el-table-column width="50">
          <template #header>
            <el-checkbox v-model="isAllSelected" :indeterminate="isIndeterminate"
              @change="handleSelectAll"></el-checkbox>
          </template>
          <template #default="{ row }">
            <el-checkbox v-model="row.selected" @click.stop @change="updateSelectAllStatus"></el-checkbox>
          </template>
        </el-table-column>
        <el-table-column label="文件名" min-width="300">
          <template #default="{ row }">
            <div class="file-name-cell">
              <div class="file-icon">
                <img v-if="row.categoryId === 3" :src="row.imageUrl || getFileIcon(row)" alt="文件图标"
                  class="file-thumbnail">
                <img v-else :src="getFileIcon(row)" alt="文件图标" class="file-thumbnail">
              </div>
              <span class="file-name" :title="row.name" @click.stop="previewFileFunc(row)">{{ row.name }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="修改时间" width="200">
          <template #default="{ row }">
            {{ formatDateTime(row.lastUpdateTime) }}
          </template>
        </el-table-column>
        <el-table-column label="大小" width="120">
          <template #default="{ row }">
            {{ formatFileSize(row.size) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <div class="file-actions">
              <el-tooltip content="分享" placement="top">
                <i class="iconfont icon-share action-icon" @click.stop="shareFile(row)"></i>
              </el-tooltip>
              <el-tooltip content="下载" placement="top">
                <i class="iconfont icon-download action-icon" @click.stop="downloadFile(row)"></i>
              </el-tooltip>
              <el-tooltip content="删除" placement="top">
                <i class="iconfont icon-del action-icon" @click.stop="deleteFile(row)"></i>
              </el-tooltip>
              <el-tooltip content="重命名" placement="top">
                <i class="iconfont icon-edit action-icon" @click.stop="renameFile(row)"></i>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[10, 20, 30, 40]"
          layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>
    </div>

    <!-- 无数据提示 -->
    <div v-else class="no-data">
      <div class="no-data-inner">
        <img src="@/assets/empty.png" alt="暂无数据" width="200">
        <div class="tips">暂无文件，快来上传吧</div>
      </div>
    </div>

    <!-- 重命名对话框 -->
    <el-dialog v-model="renameDialogVisible" title="重命名" width="30%">
      <el-input v-model="newFileName" placeholder="请输入新文件名"></el-input>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="renameDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmRename">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 分享对话框 -->
    <el-dialog v-model="shareDialogVisible" title="分享" width="30%">
      <div class="share-dialog-content">
        <div class="file-info-share">文件 {{ currentFile?.name }}</div>

        <div class="share-option">
          <div class="option-label"><span class="required">*</span> 有效期</div>
          <div class="option-content">
            <el-radio-group v-model="shareForm.validType">
              <el-radio :label="0">1天</el-radio>
              <el-radio :label="1">7天</el-radio>
              <el-radio :label="2">30天</el-radio>
              <el-radio :label="3">永久有效</el-radio>
            </el-radio-group>
          </div>
        </div>

        <div class="share-option">
          <div class="option-label"><span class="required">*</span> 提取码</div>
          <div class="option-content">
            <el-radio-group v-model="shareForm.codeType">
              <el-radio :label="0">自定义</el-radio>
              <el-radio :label="1">系统生成</el-radio>
            </el-radio-group>
          </div>
        </div>

        <div class="share-option" v-if="shareForm.codeType === 0">
          <el-input v-model="shareForm.code" placeholder="请输入5位提取码" maxlength="5">
            <template #prepend>提取码</template>
          </el-input>
          <div class="error-tip" v-if="codeError">请输入提取码</div>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="shareDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmShare">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 分享成功对话框 -->
    <el-dialog v-model="shareSuccessDialogVisible" title="分享成功" width="30%">
      <div class="share-success-content">
        <div class="share-item">
          <div class="share-item-label">文件</div>
          <div class="share-item-value">{{ shareResult.fileName }}</div>
        </div>
        <div class="share-item">
          <div class="share-item-label">分享链接</div>
          <div class="share-item-value">
            <el-input v-model="shareResult.shareUrl" readonly></el-input>
            <el-button type="primary" size="small" @click="copyText(shareResult.shareUrl)">复制</el-button>
          </div>
        </div>
        <div class="share-item" v-if="shareResult.code">
          <div class="share-item-label">提取码</div>
          <div class="share-item-value">
            <el-input v-model="shareResult.code" readonly></el-input>
            <el-button type="primary" size="small" @click="copyText(shareResult.code)">复制</el-button>
          </div>
        </div>
        <div class="share-item">
          <el-button type="primary" @click="copyShareInfo">复制链接及提取码</el-button>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="shareSuccessDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 文件预览组件 -->
    <Preview v-model:visible="previewDialogVisible" :file="currentPreviewFile" @download="downloadFile" />

    <Uploader ref="uploaderRef" :showUploader="showUploaderWindow" @uploadCallback="uploadCallback"></Uploader>
  </div>
</template>

<script setup>
import Uploader from "@/views/main/Uploader.vue";
import Preview from "@/views/Preview.vue";
import { ref, onMounted, computed, watch, defineExpose, inject } from "vue";
import { useRoute } from "vue-router";
import { fileListService, getImageService, fileRenameService, delFileService, downloadFileService, shareFileService } from "@/api/file.js";
import { getPreviewUrl } from "@/api/preview.js";
import { ElMessage, ElMessageBox } from 'element-plus';
import { useFileList, copyText } from "@/assets/js/file.list.js";

const route = useRoute();
const uploaderRef = ref();

// 注入从Home.vue提供的上传窗口状态和空间刷新方法
const showUploaderWindow = inject('showUploaderWindow', ref(false));
const refreshUserSpace = inject('refreshUserSpace', () => { });

// 分享相关
const shareDialogVisible = ref(false);
const shareSuccessDialogVisible = ref(false);
const shareForm = ref({
  fileId: null,
  validType: 0, // 默认1天
  codeType: 1, // 默认系统生成
  code: ''
});
const codeError = ref(false);
const shareResult = ref({
  fileName: '',
  shareUrl: '',
  code: ''
});

// 使用通用文件列表逻辑
const {
  fileList,
  currentPage,
  pageSize,
  total,
  searchName,
  selectedFiles,
  isAllSelected,
  isIndeterminate,
  previewDialogVisible,
  currentPreviewFile,
  renameDialogVisible,
  newFileName,
  currentFile,
  currentCategory,
  currentCategoryName,
  getDefaultCoverByCategory,
  getFileIcon,
  formatFileSize,
  formatDateTime,
  loadFileList,
  handleSizeChange,
  handleCurrentChange,
  searchFiles,
  refreshFileList,
  updateSelectedFiles,
  updateSelectAllStatus,
  handleSelectAll,
  handleRowClick,
  previewFileFunc,
  downloadFile: baseDownloadFile,
  renameFile,
  confirmRename: baseConfirmRename,
  watchCategoryChange
} = useFileList({
  loadDataService: (params) => fileListService({ ...params, delFlag: 1 }), // 未删除的文件
  categoryNames: {
    'all': '全部',
    'video': '视频',
    'music': '音频',
    'image': '图片',
    'doc': '文档',
    'zip': '压缩包',
    'others': '其他'
  }
});

// 监听路由变化
watchCategoryChange(watch);

// 监听上传状态变化，当上传文件时自动显示上传窗口
watch(() => uploaderRef.value?.fileList?.length, (newVal) => {
  if (newVal > 0) {
    showUploaderWindow.value = true;
  }
});

// 下载文件
const downloadFile = async (file) => {
  await baseDownloadFile(file, downloadFileService);
};

// 确认重命名
const confirmRename = async () => {
  await baseConfirmRename(fileRenameService);
};

// 添加文件
const addFile = (file) => {
  uploaderRef.value.addFile(file.file);
};

// 上传回调
const uploadCallback = () => {
  loadFileList();
  refreshUserSpace(); // 使用Home.vue提供的刷新方法
};

// 删除单个文件
const deleteFile = (file) => {
  ElMessageBox.confirm(
    `确定要删除文件 "${file.name}" 吗？`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    try {
      await delFileService([file.id]);
      ElMessage.success('删除成功');
      loadFileList();
    } catch (error) {
      console.error('删除文件失败:', error);
      ElMessage.error('删除文件失败');
    }
  }).catch(() => {
    // 取消删除
  });
};

// 批量删除文件
const batchDeleteFiles = () => {
  // 再次确认选中的文件数量
  updateSelectedFiles();

  if (selectedFiles.value.length === 0) {
    ElMessage.warning('请至少选择一个文件');
    return;
  }

  ElMessageBox.confirm(
    `确定要删除选中的 ${selectedFiles.value.length} 个文件吗？`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    try {
      const fileIds = selectedFiles.value.map(file => file.id);
      await delFileService(fileIds);
      ElMessage.success('删除成功');
      loadFileList();
    } catch (error) {
      console.error('删除文件失败:', error);
      ElMessage.error('删除文件失败');
    }
  }).catch(() => {
    // 取消删除
  });
};

// 分享文件
const shareFile = (file) => {
  currentFile.value = file;
  shareForm.value = {
    fileId: file.id,
    validType: 0, // 默认1天
    codeType: 1, // 默认系统生成
    code: ''
  };
  codeError.value = false;
  shareDialogVisible.value = true;
};

// 确认分享
const confirmShare = async () => {
  // 验证提取码
  if (shareForm.value.codeType === 0 && !shareForm.value.code) {
    codeError.value = true;
    return;
  }

  try {
    // 如果是系统生成提取码，则code传null
    const params = {
      ...shareForm.value,
      fileName: currentFile.value.name // 添加fileName参数
    };
    if (params.codeType === 1) {
      params.code = null;
    }

    const result = await shareFileService(params);
    if (result && result.data) {
      // 显示分享成功对话框
      shareResult.value = {
        fileName: currentFile.value.name,
        shareUrl: `${document.location.origin}/getShare/${result.data.id}`,
        code: result.data.code || ''
      };
      shareDialogVisible.value = false;
      shareSuccessDialogVisible.value = true;
    }
  } catch (error) {
    console.error('分享失败:', error);
    ElMessage.error('分享失败');
  }
};

// 复制分享信息（链接和提取码）
const copyShareInfo = () => {
  let text = `分享链接：${shareResult.value.shareUrl}`;
  if (shareResult.value.code) {
    text += `\n提取码：${shareResult.value.code}`;
  }
  copyText(text);
};

// 添加控制上传窗口显示/隐藏的方法
const toggleUploaderWindow = () => {
  showUploaderWindow.value = !showUploaderWindow.value;
};

onMounted(() => {
  loadFileList();
});

// 暴露方法给父组件
defineExpose({
  toggleUploaderWindow
});
</script>

<style lang="scss" scoped>
@use "@/assets/file.list.scss";

// Main.vue 特有样式
.no-data {
  height: 400px; // Main.vue 特有的高度设置
}

.share-dialog-content {
  .file-info-share {
    margin-bottom: 20px;
    font-size: 14px;
  }

  .share-option {
    margin-bottom: 15px;

    .option-label {
      font-size: 14px;
      margin-bottom: 8px;

      .required {
        color: red;
      }
    }

    .option-content {
      .el-radio {
        margin-right: 10px;
      }
    }
  }

  .error-tip {
    color: #f56c6c;
    font-size: 12px;
    margin-top: 5px;
  }
}

.share-success-content {
  .share-item {
    margin-bottom: 15px;

    .share-item-label {
      font-size: 14px;
      margin-bottom: 8px;
    }

    .share-item-value {
      display: flex;
      align-items: center;
      gap: 10px;
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .preview-footer {
    flex-direction: column;
    align-items: stretch;

    .file-info {
      justify-content: center;
    }
  }
}
</style>